<?php
/**
 * User: hjd-yao
 * Date: 2019/2/15
 * Time: 11:23
 */

namespace App\Models;

use Carbon\Carbon;

trait AdminLoginLimit
{
    public $loginCountKey;
    public $loginLockKey;

    public function getLoginCountKey($mgr_name)
    {
        $this->loginCountKey = 'backend_'.$mgr_name.'_error_num';
        return $this->loginCountKey;
    }

    public function getLoginLockKey($mgr_name)
    {
        $this->loginLockKey = 'backend_'.$mgr_name.'_lock';
        return  $this->loginLockKey;
    }

    public function errorCountLimit($mgr_name)
    {
        $key = $this->getLoginCountKey($mgr_name);
        $error_num = cache()->get($key);
        $error_num = $error_num?$error_num:0;
        if($error_num>=10){
            self::where('mgr_name',$mgr_name)->update(['is_lock',1]);
            cache()->forever($this->getLoginLockKey($mgr_name),'is_lock');
        }elseif($error_num>=5){
            $lock_key = $this->getLoginLockKey($mgr_name);
            $expiresAt = Carbon::now()->addMinutes(30+($error_num-5)*30);
            cache()->put($lock_key,$expiresAt,$expiresAt);
        }
        cache()->put($key,$error_num+1,24*60);
        return $error_num+1;
    }

    public function loginLimit($mgr_name)
    {
        $expiresAt = cache()->get($this->getLoginLockKey($mgr_name));
        if(!$expiresAt){
            return true;
        }
        if($expiresAt == 'is_lock'){
            $this->errorMsg = '账号被锁定,请联系技术人员解锁';
            return false;
        }
        $this->errorMsg = '请'.($expiresAt->timestamp-time()).'秒后再试';
        return false;
    }

    public function clearLoginLimit($mgr_name)
    {
        cache()->forget($this->getLoginCountKey($mgr_name));
        cache()->forget($this->getLoginLockKey($mgr_name));
    }

}